package com.xmg.leetCode;

import java.util.HashMap;
import java.util.Map;

/**
 * 给定一个字符串，请你找出其中不含有重复字符的 最长子串 的长度。
 */
public class No3 {
    public static void main(String[] args) {
        String s = "abcabcbb";
        System.out.println(Solution3B.lengthOfLongestSubstring(s));
    }
}

class Solution3 {
    public static int lengthOfLongestSubstring(String s) {
        if(s==null || s.length()==0){
            return 0;
        }
        int max = 0;
        byte[] bytes = s.getBytes();
        Map<Byte,Object> map = new HashMap<>();
        int index = 0;
        int res = 0;
        while (index<bytes.length){
            if(map.size()==0){
                res = index;
            }
            if(map.containsKey(bytes[index])){
                max = Math.max(max,map.size());
                map.clear();
                index = res+1;
            }else{
                map.put(bytes[index],null);
                index++;
            }
        }
        return Math.max(max,map.size());
    }
}

class Solution3B {
    public static int lengthOfLongestSubstring(String s) {
        Map<Character,Integer> map = new HashMap<>();
        int max = 0;
        for (int start = 0,end = 0; end < s.length(); end++) {
            char ele = s.charAt(end);
            if(map.containsKey(ele)){
                start = Math.max(map.get(ele)+1,start); //从发现的重复字符的下一位开始继续查找
            }
            max = Math.max(max,end-start+1);
            map.put(ele,end);
        }
        return max;
    }
}